package com.ccys.doctor.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.ccys.common.util.Kit;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.TranslationUtil;
import com.ccys.db.entity.TblMember;
import com.ccys.db.cache.TranslationUtil;
import com.ccys.db.mapper.TblBookingDiagnosisMapper;
import com.ccys.db.mapper.TblBookingMapper;
import com.ccys.db.mapper.TblMemberMapper;
import com.ccys.db.mapper.TblRecommendReminderMapper;
import com.ccys.db.page.AppPageDto;
import com.ccys.db.page.PageDto;
import com.ccys.db.vo.doctor.passHistoryConsultants.*;
import com.ccys.doctor.service.PassHistoryConsultantsService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @program: WhiteCoat
 * @description: PassHistoryConsultants相关接口
 * @author: ZhangJingCan
 * @create: 2024-02-07 17:29
 **/

@Service
public class PassHistoryConsultantsServiceImpl implements PassHistoryConsultantsService {

    @Resource
    private TblBookingMapper tblBookingMapper;

    @Resource
    private TblBookingDiagnosisMapper tblBookingDiagnosisMapper;

    @Resource
    private TblRecommendReminderMapper recommendReminderMapper;

    @Resource
    private TblMemberMapper memberMapper;

    @Resource
    private TblMemberMapper tblMemberMapper;

    @Override
    public ResponseResultApp<GetPassHistoryConsultantsPagingVo> getPassHistoryConsultantsPaging(String memberId, String pageIndex, String pageSize, String childId) {
        if (ObjectUtil.isEmpty(memberId) || ObjectUtil.isEmpty(pageIndex) || ObjectUtil.isEmpty(pageSize)) {
            return ResponseResultApp.error("Parameter abnormality");
        }
        //先查询booking - 这里要分页查询 - 但是对方postman并没有返回总页数 - 所以只是按照分页查询即可
        List<ConsultantsMakeVo> consultants = tblBookingMapper.getPassHistoryConsultantsPaging(memberId, pageIndex, pageSize, childId);
        List<DiagnosisMakeVo> diagnosisMakeVos = tblBookingMapper.findListDiagnosisByMemberId(memberId, childId);
        if (ObjectUtil.isNotEmpty(consultants)) {
            consultants.forEach(item -> {
                //设置从创建至今过去了多少天
                item.setCreatedOnDisplay("about " + Kit.calculateDaysSinceDate(item.getTimezoneCreatedOn()) + " days ago");
            });
        }
        //翻译
        diagnosisMakeVos.forEach(item -> {
            String trans = TranslationUtil.getContentLastLanguage(item.getMdDiagnosisName(), tblMemberMapper.selectByPrimaryKey(memberId).getCurrentLanguage());
            item.setTransName(StringUtils.isBlank(trans) ? item.getMdDiagnosisName() : trans);
        });

        GetPassHistoryConsultantsPagingVo vo = new GetPassHistoryConsultantsPagingVo();
        vo.setConsultants(consultants);
        vo.setDiagnosis(diagnosisMakeVos);
        return ResponseResultApp.success(vo);
    }

    @Override
    public ResponseResultApp<GetPassHistoryConsultantsVo> getPassHistoryConsultants(String memberId, String pageIndex, String pageSize, String childId) {
        if (ObjectUtil.isEmpty(memberId) || ObjectUtil.isEmpty(pageIndex) || ObjectUtil.isEmpty(pageSize)) {
            return ResponseResultApp.error("Parameter abnormality");
        }
        //返回对象
        GetPassHistoryConsultantsVo vo = new GetPassHistoryConsultantsVo();
        //开启分页
        AppPageDto.startPage();
        //主数据
        List<GetPassHistoryConsultantsMakeVo> consultantsMakeVos = tblBookingMapper.getPassHistoryConsultants(memberId, childId);
        PageInfo<GetPassHistoryConsultantsMakeVo> pageInfo = new PageInfo<>(consultantsMakeVos);
        consultantsMakeVos.forEach(item -> {
            //设置从创建至今过去了多少天
            item.setCreatedOnDisplay("about " + Kit.calculateDaysSinceDate(item.getTimezoneCreatedOn()) + " days ago");
        });

        //诊断数据
        List<GetPassHistoryConsultantsDiagnosisMakeVo> diagnosisMakeVos = tblBookingDiagnosisMapper.findDiagnosisByMemberId(memberId, childId);
        //根据bookingId分组
        // 使用Stream API进行分组、排序和设置排序值
        Map<String, List<GetPassHistoryConsultantsDiagnosisMakeVo>> groupedByBookingId = diagnosisMakeVos.stream()
                .sorted(Comparator.comparing(GetPassHistoryConsultantsDiagnosisMakeVo::getCreatedDate).reversed())
                .collect(Collectors.groupingBy(GetPassHistoryConsultantsDiagnosisMakeVo::getBookingId));

        AtomicInteger counter = new AtomicInteger(1); // 用于给排序字段赋值

        // 遍历分组后的数据，给排序字段赋值
        groupedByBookingId.forEach((bookingId, list) -> {
            list.forEach(item -> {
                item.setMDDiagnosisDispOrder(counter.getAndIncrement());
                //翻译
                String trans = TranslationUtil.getContentLastLanguage(item.getMDDiagnosisName(), tblMemberMapper.selectByPrimaryKey(memberId).getCurrentLanguage());
                item.setTransName(StringUtils.isBlank(trans) ? item.getMDDiagnosisName() : trans);
            });
        });
        vo.setTotalPage(pageInfo.getPages());
        vo.setConsultants(consultantsMakeVos);
        vo.setDiagnosis(diagnosisMakeVos);
        return ResponseResultApp.success(vo);
    }

    @Override
    public ResponseResultApp getPassHistoryRecommend(String memberId, String recommend_type) {
        AppPageDto.startPage();
        PageInfo<HistoryRecommendVo> pageInfo = new PageInfo<>(recommendReminderMapper.selectHistoryRecommendList(memberId, recommend_type));
        List<HistoryRecommendVo> list = pageInfo.getList();
        if(list.isEmpty()){
            return ResponseResultApp.success("There is no consultant",null);
        }
        Integer negative;
        Date utcDateToTakeRecommend;
        for (HistoryRecommendVo vo : list) {
            utcDateToTakeRecommend = vo.getUtcDateToTakeRecommend();
            String timezoneWhenCreating = vo.getTimezoneWhenCreating();
            negative = timezoneWhenCreating.contains("-")?-1:1;
            String[] split = timezoneWhenCreating.replaceAll("\\+", "").replace("\\-", "").split(":");
            Date dateTime = Kit.getTimeByTimeZone(utcDateToTakeRecommend, Integer.valueOf(split[0]) * negative);
            vo.setStartDate(DateUtil.format(dateTime,"yyyy-MM-dd")+"T00:00:00");
            vo.setStartTime(DateUtil.format(dateTime,"HH:mm:ss"));
            vo.setDate(DateUtil.format(dateTime,"dd/MM/yyyy"));
            vo.setTime(DateUtil.format(dateTime,"hh:mma"));
        }
        JSONObject json = new JSONObject();
        json.put("total_page",pageInfo.getPages());
        json.put("recommends",list);
        return ResponseResultApp.success(json);
    }

    @Override
    public ResponseResultApp<GetPassHistoryConsultantsInitVo> getPassHistoryConsultantsInit(String memberId, String pageIndex, String pageSize, String childId) {
        if (ObjectUtil.isEmpty(memberId) || ObjectUtil.isEmpty(pageIndex) || ObjectUtil.isEmpty(pageSize)) {
            return ResponseResultApp.error("Parameter abnormality");
        }
        //开启分页
        AppPageDto.startPage();
        //主数据
        List<HistoryConsultantsInitMakeVo> list = tblBookingMapper.getPassHistoryConsultantsInit(memberId, childId);
        PageInfo<HistoryConsultantsInitMakeVo> pageInfo = new PageInfo<>(list);
        list.forEach(item -> {
            //设置从创建至今过去了多少天
            item.setCreatedOnDisplay("about " + Kit.calculateDaysSinceDate(item.getTimezoneCreatedOn()) + " days ago");
        });
        //查询诊断
        List<DiagnosisMakeVo> diagnosisMakeVos = tblBookingMapper.findListDiagnosisByMemberId(memberId, childId);
        //翻译
        diagnosisMakeVos.forEach(item -> {
            String trans = TranslationUtil.getContentLastLanguage(item.getMdDiagnosisName(), tblMemberMapper.selectByPrimaryKey(memberId).getCurrentLanguage());
            item.setTransName(StringUtils.isBlank(trans) ? item.getMdDiagnosisName() : trans);
        });
        //返回对象
        GetPassHistoryConsultantsInitVo vo = new GetPassHistoryConsultantsInitVo();
        vo.setTotalPage(pageInfo.getPages());
        vo.setConsultants(list);
        vo.setDiagnosis(diagnosisMakeVos);
        return ResponseResultApp.success(vo);
    }

    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh a");
        System.out.println(DateUtil.format(date,"hh:mma"));
    }
}
